<template>
    <div class="exam-container">
        <div class="main-content">
            <div v-for="(question, index) in sortedQuestions" :key="question.id" class="question-card"
                 :id="`question-${question.id}`">
                <div slot="header" class="card-header">
                    <div class="header-wrapper">
                        <div class="title-tag">
                            第 {{ index + 1 }} 题（{{ typeMap[question.questionType] }},分值:{{ question.score }}
                            <span v-if="question.questionType === '4'">,多个答案用英文,符隔开</span>）
                        </div>
                    </div>
                </div>

                <div class="question-content">
                    <div class="question-text">{{ question.questionText }}</div>

                    <!-- 单选题 -->
                    <div v-if="question.questionType === '1'" class="option-group">
                        <el-radio-group :model-value="parseAnswer(question.answer)[0]">
                            <el-radio v-for="(option, i) in parseOptions(question.chooseOption)" :key="i"
                                      :label="String.fromCharCode(65 + i)"
                                      :class="getAnswerClass(question, String.fromCharCode(65 + i))"
                                      disabled>
                                <div class="option-content">
                                    {{ String.fromCharCode(65 + i) }}. {{ option }}
                                </div>
                            </el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 多选题 -->
                    <div v-else-if="question.questionType === '2'" class="option-group">
                        <el-checkbox-group :model-value="parseAnswer(question.answer)">
                            <el-checkbox v-for="(option, i) in parseOptions(question.chooseOption)" :key="i"
                                         :label="String.fromCharCode(65 + i)"
                                         :class="getAnswerClass(question, String.fromCharCode(65 + i))"
                                         disabled>
                                <div class="option-content">{{ String.fromCharCode(65 + i) }}. {{ option }}</div>
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>

                    <!-- 判断题 -->
                    <div v-else-if="question.questionType === '3'" class="option-group vertical">
                        <el-radio-group :model-value="parseAnswer(question.answer)[0]">
                            <el-radio label="T"
                                      :class="getAnswerClass(question, 'T')"
                                      disabled>
                                <div class="option-content">正确</div>
                            </el-radio>
                            <el-radio label="F"
                                      :class="getAnswerClass(question, 'F')"
                                      disabled>
                                <div class="option-content">错误</div>
                            </el-radio>
                        </el-radio-group>
                    </div>

                    <!-- 填空题 -->
                    <div v-else-if="question.questionType === '4'" class="option-group">
                        <div class="answer-comparison">
                            <div class="correct-answer">正确答案：{{ parseAnswer(question.answer).join(', ') }}</div>
                        </div>
                    </div>

                    <!-- 答案解析 -->
                    <!--<div class="answer-analysis">-->
                        <!--<el-divider />-->
                        <!--<div class="analysis-title">答案解析：</div>-->
                        <!--<div class="analysis-content">{{ question.answerAnaly || '暂无解析' }}</div>-->
                    <!--</div>-->
                </div>
            </div>
        </div>

        <!-- 右侧导航栏 -->
        <div class="right-nav">
            <div class="nav-buttons">
                <el-button v-for="(question, index) in sortedQuestions" class="round-button"
                           @click="scrollToQuestion(index)" :key="question.id"
                           :class="['nav-button', 'correct']">
                    {{ index + 1 }}
                </el-button>
            </div>
        </div>
    </div>
</template>

<script>
    import request from "~/utils/request.js";

    export default {
        name: 'trueResult',
        data() {
            return {
                studentInfo: {name: '张三'},
                typeMap: {
                    '1': '单选题',
                    '2': '多选题',
                    '3': '判断题',
                    '4': '填空题'
                },
                questions: [],
                answers: [],
            };
        },
        computed: {
            sortedQuestions() {
                return [...this.questions].sort((a, b) =>
                    a.questionType.localeCompare(b.questionType))
            },
        },
        // watch 部分增加类型校验
        watch: {
            sortedQuestions: {
                immediate: true,
                handler(newVal) {
                    this.answers = newVal.map(q => {
                        // 确保多选题初始化为数组，其他类型初始化为空字符串
                        return q.questionType === '2' ? [] : '';
                    });
                }
            }
        },
        activated() {
            this.load();
        },
        methods: {
            parseAnswer(answer) {
                try {
                    if (typeof answer === 'string') {
                        // 去除首尾双引号和方括号
                        const cleaned = answer
                            .replace(/^"+|"+$/g, '')  // 去除首尾双引号
                            .replace(/^\[|\]$/g, ''); // 去除首尾方括号

                        // 尝试解析JSON格式
                        try {
                            const parsed = JSON.parse(`[${cleaned}]`); // 包裹成数组格式解析
                            return parsed.filter(item => item !== '');
                        } catch {
                            // 处理逗号分隔的字符串
                            return cleaned.split(',').map(item =>
                                item.trim().replace(/^"+|"+$/g, '') // 去除每个元素的双引号
                            );
                        }
                    }
                    return Array.isArray(answer) ? answer : [answer];
                } catch {
                    return [answer];
                }
            },

            getAnswerClass(question, option) {
                const correctAnswer = this.parseAnswer(question.answer);

                // 转换为字符串比较（兼容大小写和类型）
                const isCorrect = correctAnswer.some(ans =>
                    ans.toString().toUpperCase() === option.toUpperCase()
                );

                if (isCorrect) return 'is-checked correct-answer';
                return '';
            },
            load() {
                request.get('exampaper/findQuestionByExampaperId', {
                    params: {
                        exampaperId: this.$route.query.examId,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.questions = res.data.records;
                    }

                });
            },
            parseOptions(options) {
                try {
                    const obj = JSON.parse(options);
                    return Object.keys(obj).sort().map(k => obj[k]);
                } catch {
                    return [];
                }
            },
            scrollToQuestion(index) {
                const questionId = this.sortedQuestions[index].id;
                const element = document.getElementById(`question-${questionId}`);
                if (element) {
                    element.scrollIntoView({behavior: 'smooth', block: 'start'});
                }
            },
        }
    };
</script>

<style scoped>
    /* 整体布局 */
    .exam-container {
        display: flex;
        height: 83vh;
        background: #f7f8fa;
    }

    /* 中间题目区 */
    .main-content {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        max-height: 100vh;
    }

    /* 右侧导航栏 */
    .right-nav {
        width: 200px;
        padding: 20px;
        background: white;
        box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
        border-left: 1px solid #ebedf0;
        display: flex;
        flex-direction: column;
    }

    /* 题目卡片 */
    .question-card {
        position: relative;
        border-radius: 15px;
        background-color: white;
        padding: 20px;
        margin-bottom: 20px;
        max-width: 800px;
        margin-left: auto;
        margin-right: auto;
    }

    /* 题头布局 */
    .header-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }

    .status-tag {
        font-size: 14px;
        padding: 6px 12px;
    }

    /* 题目内容 */
    .question-text {
        font-size: 18px;
        color: #333;
        line-height: 1.6;
        margin-bottom: 20px;
    }

    /* 选项通用样式 */
    .option-content {
        font-size: 16px;
        padding: 8px;
        color: #333;
    }

    /* 移除选项背景色相关样式 */
    .correct-answer .option-content {
        background: none;
        border-radius: 0;
    }

    /* 强化圆圈选中状态 */
    .el-radio.is-checked.correct-answer .el-radio__inner {
        background-color: #67c23a !important;
        border-color: #67c23a !important;
    }

    /* 多选框选中状态 */
    .el-checkbox.is-checked.correct-answer .el-checkbox__inner {
        background-color: #67c23a !important;
        border-color: #67c23a !important;
    }

    /* 填空题对比 */
    .answer-comparison div {
        margin: 8px 0;
        padding: 8px;
        border-radius: 4px;
    }
    .correct-answer { background-color: #67c23a; }

    /* 答案解析 */
    .answer-analysis {
        margin-top: 25px;
        padding: 15px;
        background-color: #67c23a;
        border-radius: 8px;
    }
    .analysis-title {
        font-weight: 500;
        color: #606266;
        margin-bottom: 10px;
    }
    .analysis-content {
        color: #909399;
        line-height: 1.6;
    }

    /* 导航按钮 */
    .nav-buttons {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
    }
    .round-button {
        border-radius: 50%;
        width: 30px;
        height: 30px;
        padding: 0;
    }
    .nav-button.correct {
        background-color: #67c23a;
        border-color: #67c23a;
        color: white;
    }
    .nav-button.incorrect {
        background-color: #f56c6c;
        border-color: #f56c6c;
        color: white;
    }

    /* 多选框对号颜色 */
    :deep(.el-checkbox.is-disabled.is-checked.correct-answer) .el-checkbox__inner::after {
        border-color: black;
    }

    :deep(.el-checkbox.is-disabled.is-checked.student-answer) .el-checkbox__inner::after {
        border-color: black;
    }

    /* 单选按钮内部圆点颜色 */
    :deep(.el-radio.is-disabled.is-checked.correct-answer) .el-radio__inner::after {
        background-color: black;
    }

    :deep(.el-radio.is-disabled.is-checked.student-answer) .el-radio__inner::after {
        background-color: black;
    }
</style>
